<template>
    <view class="page-shopping-cart bg-content">
        <div v-for="(tbStore, index) in tbStoreList" :key="tbStore.id" style="margin-bottom: 10px; background-color: #FFFFFF; ">
            <div>
                <div class="table">
                    <div class="tr">
                        <div class="td" style="width: 30px !important; padding-top: 3px; padding-left: 10px; margin-right: 5px;">
                            <u-checkbox size="45" shape="circle" :value="tbStore.checked" @change="onCheckboxStoreChange($event, tbStore)"
                                        :key="tbStore.id" active-color="red"></u-checkbox>
                        </div>
                        <div class="td">
                            <span @click="navigateTo('/pages/common/store/index', {storeId: tbStore.id})">
                                <image src="/static/icon/shop.png" class="store-brand"></image>{{tbStore.name}}&nbsp;
                                <u-icon name="arrow-right"/>
                            </span>
                            <u-button type="warning" size="mini" v-if="tbStore.tbStorePromotion"
                                      @click="showTbStorePromotion(tbStore.tbStorePromotion.id, '店铺')">下单促销中
                            </u-button>
                        </div>
                    </div>
                </div>
            </div>
            <div style="background-color: #FFFFFF; padding-bottom: 2px;">
                <view class="goods-list" style="display: flex; margin-bottom: 6px;"
                      :style="{'background-color': item.id === removeShoppingCartId ? $u.color['errorDisabled'] : '#FFFFFF'}"
                      v-for="(item, index2) in tbStore.tbShoppingCartList" :key="item.id" @longpress="removeShoppingCart(item)">

                    <div style="width: 40px; padding-left: 11px; padding-top: 60px;">
                        <u-checkbox size="45" shape="circle" :value="item.checked" @change="onCheckboxChange($event, item, tbStore)" :key="item.id"
                                    active-color="red"></u-checkbox>
                    </div>
                    <view @click.stop.prevent="navigateTo(`/pages/common/goods-detail/index?id=${item.tbGoods.id}`)">
                        <image style="height: 100px; width: 100px; padding-top: 15px;"
                               :src="item.tbGoods.thumbnailUrl ? item.tbGoods.thumbnailUrl + '?imageView2/1/w/300/h/300' : '/static/default-image/goods.jpg'"
                               mode="aspectFill"></image>
                    </view>
                    <view style="padding: 6px 5px 5px 10px; width: 100%;">
                        <view style="min-height: 82px; overflow: hidden;">
                            <div style="font-size: 14px;" @click.stop.prevent="navigateTo(`/pages/common/goods-detail/index?id=${item.tbGoods.id}`)">
                                {{item.tbGoods.title}}
                            </div>
                            <div style="padding-top: 2px; padding-bottom: 2px;"
                                 @click.stop.prevent="navigateTo(`/pages/common/goods-detail/index?id=${item.tbGoods.id}`)">
                                <u-tag :text="'规格：' + item.tbGoodsSpecification.name" mode="plain" size="mini" style="margin-right: 5px;"/>
                                <u-tag v-if="item.tbGoodsColor" :text="'颜色：' + item.tbGoodsColor.name" mode="plain" size="mini"/>
                            </div>
                            <div>
                                <u-button type="warning" size="mini" v-if="item.tbGoodsSpecification.tbStorePromotion"
                                          @click="showTbStorePromotion(item.tbGoodsSpecification.tbStorePromotion.id)">商品促销中
                                </u-button>
                            </div>
                        </view>
                        <view style="display: flex; border-bottom: 1px solid #eeeeee; padding-bottom: 4px;"
                              :style="{'border-bottom': tbStore.tbShoppingCartList.length - 1 === index2 ? '0px' : '1px solid #eeeeee'}">
                            <view style="font-weight: bold; color: red; padding-top: 5px;">
                                ￥{{item.tbGoodsSpecification.price | toFixed2}}
                            </view>
                            <view style="width: 100%; text-align: right; padding-right: 5px;">
                                <u-number-box size="18" :value="item.quantity" :min="1" :max="999" :key="item.id" :long-press="false"
                                              @blur="valueChange($event, item)" @minus="valueChange($event, item)"
                                              @plus="valueChange($event, item)"></u-number-box>
                            </view>
                        </view>

                    </view>
                </view>
            </div>
        </div>

        <div class="custom-bottom-bar" :style="{'margin-bottom': currentRouteUrl === 'pages/sub/sub1-tabs/tabs/index' ? '50px' : 'unset'}">
            <span style="width: 100%; padding-top: 8px; padding-right: 10px; text-align: right;">
                合计：<span style="color: red;">￥</span>
                <u-count-to :start-val="startVal" :end-val="totPrice" :duration="500" :color="$u.color['error']" :decimals="2" :bold="true"
                            :use-easing="false"></u-count-to>
            </span>
            <span style="padding-top: 5px; padding-right: 6px;">
                <u-button type="error" shape="circle" :custom-style="{width: '100px'}" @click="gotoOrderAddPage()">去结算</u-button>
            </span>
        </div>

        <div style="padding-bottom: 62px;" v-if="tbShoppingCartList.length">
            <u-loadmore :status="'nomore'" bg-color="#eeeeee"/>
        </div>

        <div style="padding-top: 50px;" v-if="!tbShoppingCartList.length">
            <u-empty text="购物车为空" mode="car"></u-empty>
        </div>

        <tbStorePromotion ref="tbStorePromotionRef"></tbStorePromotion>
    </view>
</template>

<script>

    import tbStorePromotion from './tb-store-promotion.vue'
    import {TbShoppingCartService} from "../dev/services/tb-shopping-cart.service";
    import {CommonUtil} from "../dev/core/utils/common.util";

    export default {
        data() {
            return {
                tbShoppingCartList: [],
                tbStoreList: [],
                startVal: 0.00,
                totPrice: 0.00,
                removeShoppingCartId: null,  // 弹框移除商品时赋予该商品的ID
            }
        },
        components: {
            tbStorePromotion
        },
        mounted() {
            this.findTbShoppingCartList()
        },
        methods: {
            findTbShoppingCartList() {
                const _self = this;
                _self.tbStoreList = []
                _self.totPrice = 0.00
                new TbShoppingCartService().findTbShoppingCartList({
                    communityId: _self.globalVariable.userInfo.tbCommunity.id,
                    userId: _self.globalVariable.userInfo.id,
                    type: '0'  // 类型：0-加入购物车，1-立即购买
                }).then(data => {
                    _self.tbShoppingCartList = data
                    _self.mergeData()
                })
            },
            showTbStorePromotion(id, typeName) {
                const _self = this;
                _self.$refs.tbStorePromotionRef.openTbStorePromotion(id, typeName);
            },
            mergeData() {
                const _self = this;
                _self.tbStoreList = []
                _self.totPrice = 0.00
                // 汇总所有店铺
                _self.tbShoppingCartList.forEach(item => {
                    item.checked = false
                    if (_self.tbStoreList.filter(tbStore => tbStore.id === item.storeId).length === 0) {
                        item.tbStore.checked = false
                        _self.tbStoreList.push(Object.assign({}, item.tbStore)) // 直接push(item.tbStore)页面调用时会报错，因为对象被循环引用
                    }
                })

                // 购物车商品按店铺分类
                _self.tbStoreList.forEach(tbStore => {
                    tbStore.tbShoppingCartList = _self.tbShoppingCartList.filter(item => item.storeId === tbStore.id)
                })
                _self.calculateTotalPrice()
            },
            /**
             * 计算总价格
             */
            calculateTotalPrice() {
                const _self = this;
                _self.startVal = _self.totPrice;
                _self.totPrice = 0.0;
                _self.tbShoppingCartList.forEach(item => {
                    if (item.checked && item.tbGoods && item.tbGoods.status === '1' && !item.tbGoods.deleted && item.tbStore.operatingStatus) {
                        _self.totPrice += item.tbGoodsSpecification.price * item.quantity
                    }
                });
                _self.$forceUpdate();
            },
            /**
             * 选中店铺下的所有商品
             */
            onCheckboxStoreChange($event, tbStore) {
                const _self = this;
                console.log($event, tbStore, tbStore.checked);
                tbStore.checked = $event.value;
                _self.$forceUpdate();

                // 选择店铺
                if (tbStore.checked) {
                    // 取消勾选其他店铺
                    _self.tbStoreList.forEach(item => {
                        if (item.id !== tbStore.id) {
                            item.checked = false;
                        }
                    });

                    // 勾选该店铺下的所有商品
                    _self.tbShoppingCartList.forEach((item, index) => {
                        if (item.storeId === tbStore.id) {
                            item.checked = true;
                        }
                    });
                } else {  // 取消选择店铺，取消勾选该店铺下的所有商品
                    _self.tbShoppingCartList.forEach(item => {
                        if (item.storeId === tbStore.id) {
                            item.checked = false;
                        }
                    });
                }

                // 是否勾选了其他店铺的商品
                let otherTbSotreGoodsList = _self.tbShoppingCartList.filter(item => item.checked && item.storeId !== tbStore.id);
                // 已经勾选了其他店铺的商品，则取消勾选并提示
                if (otherTbSotreGoodsList.length) {
                    CommonUtil.toast('只能勾选相同店铺下的商品');
                    otherTbSotreGoodsList.forEach(item => {
                        item.checked = false;
                        _self.tbStoreList.forEach(tbStore => {
                            if (tbStore.id === item.storeId) {
                                tbStore.checked = false;
                            }
                        });
                    });
                }

                _self.calculateTotalPrice();
            },
            onCheckboxChange($event, item, tbStore) {
                const _self = this;
                console.log($event, item, tbStore, item.checked);
                item.checked = $event.value;
                _self.$forceUpdate();

                let tbGoods = item.tbGoods;
                let otherTbSotreGoodsList = _self.tbShoppingCartList.filter(item => item.checked && item.storeId !== tbGoods.storeId);
                // 已经勾选了其他店铺的商品，则取消勾选并提示
                if (otherTbSotreGoodsList.length) {
                    CommonUtil.toast('只能勾选相同店铺下的商品');
                    otherTbSotreGoodsList.forEach(item => {
                        item.checked = false;
                        _self.tbStoreList.forEach(tbStore => {
                            if (tbStore.id === item.storeId) {
                                tbStore.checked = false;
                            }
                        });
                    });
                }

                // 判断是否需要勾选 全选按钮
                let uncheckedList = _self.tbShoppingCartList.filter(item => !item.checked && item.storeId === tbGoods.storeId);
                if (uncheckedList.length === 0) {  // 全部选中
                    tbStore.checked = true;
                } else { // 存在没选中的
                    tbStore.checked = false;
                }

                _self.calculateTotalPrice();
            },
            /**
             * 购买数量
             */
            valueChange($event, item) {
                console.log(item.quantity)
                console.log($event)
                const _self = this;
                item.quantity = $event.value;
                new TbShoppingCartService().updateTbShoppingCart({
                    id: item.id,
                    quantity: item.quantity
                }).then(result => {
                    _self.calculateTotalPrice()
                })
            },
            removeShoppingCart(removeItem) {
                const _self = this;
                _self.removeShoppingCartId = removeItem.id;
                CommonUtil.alert({
                    title: '提示',
                    content: '确认移除购物车吗？',
                    showCancel: true, // 是否显示取消按钮
                    cancelText: '取消', // 默认是“取消”
                    confirmText: '确定', // 默认是“确定”
                    success: function (res) {
                        _self.removeShoppingCartId = null;
                        if (res.cancel) {
                            // 点击取消,默认隐藏弹框
                        } else {
                            // 点击确定
                            let ids = []
                            _self.tbShoppingCartList.forEach(item => {
                                if (item.id === removeItem.id) {
                                    ids.push(item.id)
                                }
                            })
                            new TbShoppingCartService().batchDeleteTbShoppingCartByIds(ids.join(',')).then(result => {
                                _self.tbShoppingCartList = _self.tbShoppingCartList.filter(item => item.id !== removeItem.id)
                                _self.mergeData()
                            })
                        }
                    }
                });
            },

            /**
             * 获得被选中店铺 每笔最小订单金额
             */
            minOrderMoney() {
                let minOrderMoney = 0.0
                this.tbShoppingCartList.forEach(item => {
                    if (item.checked) {
                        minOrderMoney = item.tbStore.minOrderMoney
                    }
                })
                return minOrderMoney
            },

            /**
             * 前往确认订单页面
             */
            gotoOrderAddPage() {
                let checkedTbShoppingCartList = this.tbShoppingCartList.filter(item => {
                    return item.checked && item.tbGoods && item.tbGoods.status === '1' && !item.tbGoods.deleted && item.tbStore.operatingStatus
                })
                if (checkedTbShoppingCartList.length === 0) {
                    CommonUtil.toast('你还没有选择商品哦');
                    return
                }
                if (this.totPrice < this.minOrderMoney()) {
                    CommonUtil.toast('该店铺满￥' + this.minOrderMoney().toFixed(2) + '可下单！');
                    return
                }

                let flag = false
                checkedTbShoppingCartList.forEach(item => {
                    if (item.quantity > item.tbGoodsSpecification.stockNumber) {
                        item.quantity = item.tbGoodsSpecification.stockNumber
                        flag = true
                    }
                })
                if (flag) {
                    CommonUtil.toast('部分商品库存不足，已调整为最大可下数量，请核实后重新提交。', 5000);
                    return
                }

                // 如果店铺是餐饮模式，先校验关联的餐饮号是否在店铺设置的餐饮号范围内
                if (checkedTbShoppingCartList[0].tbStore.saleMode === '2') {
                    // 如果绑定的餐饮号无效，则不能前往确认订单页面
                    if (`,${checkedTbShoppingCartList[0].tbStore.orderSequenceNumbers},`.indexOf(`,${this.globalVariable.orderSequenceNumber},`) === -1) {
                        CommonUtil.alert('请先扫码获取餐饮号');
                        return;
                    }
                }

                let shoppingCartIds = [];
                checkedTbShoppingCartList.forEach((item, index) => {
                    shoppingCartIds.push(item.id);
                });

                // 将勾选的商品保存在全局变量中，在确定订单页面直接获取
                // checkedTbShoppingCartList[0].tbStore.saleMode = '2';
                console.log('商品销售模式：' + checkedTbShoppingCartList[0].tbStore.saleModeText);
                if (checkedTbShoppingCartList[0].tbStore.saleMode === '0') { // 物流模式
                    uni.navigateTo({
                        url: `/pages/sub/sub1-tabs/tabs/shopping-cart/order-add/index?shoppingCartIds=${shoppingCartIds.join(',')}`
                    })
                } else if (checkedTbShoppingCartList[0].tbStore.saleMode === '1') { // 消费券模式
                    uni.navigateTo({
                        url: `/pages/sub/sub1-tabs/tabs/shopping-cart/consumer-voucher-add/index?shoppingCartIds=${shoppingCartIds.join(',')}`
                    })
                } else if (checkedTbShoppingCartList[0].tbStore.saleMode === '2') { // 餐饮店模式
                    uni.navigateTo({
                        url: `/pages/sub/sub1-tabs/tabs/shopping-cart/eatery-order-add/index?shoppingCartIds=${shoppingCartIds.join(',')}`
                    })
                }
            }
        }
    }
</script>

<style lang="scss" scoped>
    .page-shopping-cart .store-brand {
        height: 18px;
        width: 18px;
        padding-left: 4px;
        padding-right: 2px;
        position: relative;
        top: 3px;
    }

    .page-shopping-cart .goodsRow {
        background-color: white !important;
        margin-bottom: 4px !important;
    }

    .page-shopping-cart .goodsItem {
        background-color: white !important;
    }
</style>
